package incidencies.android.es;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.util.Xml;

public class TransParser {

	// names of the XML tags
	static final String ROOT = "rss";
	static final String TITLE = "title";
	static final String CHANNEL = "channel";
	static final String ITEM = "item";
	static final String PUB_DATE = "pubDate";

	static final String DESCRIPTION = "description";

	private InputStream input = null;

	int contadorItems = 0;
	private URL feedUrl = null;

	protected TransParser(String URL) throws MalformedURLException {

		this.feedUrl = new URL(URL);

	}

	public  TransParser(InputStream input) {
		this.input = input;

	}

	protected InputStream getInputStream() throws FileNotFoundException {
		if (this.input == null) {
			try {
				return feedUrl.openConnection().getInputStream();
			} catch (FileNotFoundException e) {
				throw new FileNotFoundException(e.getMessage());
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		} else {
			return this.input;
		}
	}

	public List<Incidencia> parse() {

		final Incidencia currentIncidencia = new Incidencia();
		RootElement root = new RootElement(ROOT);
		final List<Incidencia> list = new ArrayList<Incidencia>();

		Element channel = root.getChild(CHANNEL);
		Element item=channel.getChild(ITEM);

		item.setEndElementListener(new EndElementListener() {
			public void end() {

				list.add(currentIncidencia.copy());
			}
		});

		listeners(item, currentIncidencia);
		try {

			Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root
					.getContentHandler());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return list;
	}

	private void listeners(Element item, Incidencia unaIncidencia) {
		final Incidencia currentIncidencia = unaIncidencia;

		item.getChild(DESCRIPTION).setEndTextElementListener(
				new EndTextElementListener() {
					public void end(String body) {
						try {
							currentIncidencia.setDescripcio(body);

						} catch (Exception e) {
							// TODO Auto-generated catch block

						}
					}
				});
		item.getChild(TITLE).setEndTextElementListener(
				new EndTextElementListener() {
					public void end(String body) {
						try {
							currentIncidencia.setTitle(body);

						} catch (Exception e) {
							// TODO Auto-generated catch block

						}
					}
				});
		item.getChild(PUB_DATE).setEndTextElementListener(
				new EndTextElementListener() {
					public void end(String body) {
						try {
							currentIncidencia.setUpdateDate(new Date(body));

						} catch (Exception e) {
							// TODO Auto-generated catch block

						}
					}
				});

	}

}